<template>
    <!-- 主内容区 -->
    <div class="student-content">
        <!-- 头像区域 -->
        <div class="avatar-section">
            <el-upload class="avatar-uploader" :before-upload="checkFileType" :action="'/api/files/upload'"
                :on-success="photoHandleSuccess" :on-error="photoHandleError" :show-file-list="false">
                <img width="100" height="100" v-if="studentInfo.photo" :src="serverIp + studentInfo.photo"
                    class="avatar">
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </div>

        <!-- 基本信息 -->
        <el-form :model="studentInfo" :rules="rules" ref="infoForm" class="info-section">
            <div class="info-row">
                <label>姓名</label>
                <span>{{ studentInfo.username }}</span>
                <label>性别</label>
                <el-form-item prop="sex">
                    <select v-if="isEditing" v-model="studentInfo.sex" style="width: 80px;">
                        <option value=0>男</option>
                        <option value=1>女</option>
                    </select>
                    <span v-else>{{ studentInfo.sex === 0 || studentInfo.sex === "0" ? "男" : "女" }}</span>
                </el-form-item>
            </div>
            <div class="info-row">
                <label>班级</label>
                <span>{{ studentInfo.className }}</span>
                <label>年龄</label>
                <el-form-item prop="age">
                    <el-input v-if="isEditing" v-model.number="studentInfo.age" type="number"></el-input>
                    <span v-else>{{ studentInfo.age }}</span>
                </el-form-item>
            </div>
            <div class="info-row">
                <label>单位</label>
                <el-form-item prop="unit">
                    <el-input v-if="isEditing" v-model="studentInfo.unit"></el-input>
                    <span v-else>{{ studentInfo.unit }}</span>
                </el-form-item>
                <label>部门</label>
                <el-form-item prop="department">
                    <el-input v-if="isEditing" v-model="studentInfo.department"></el-input>
                    <span v-else>{{ studentInfo.department }}</span>
                </el-form-item>
            </div>
            <div class="info-row">
                <label>科室</label>
                <el-form-item prop="section">
                    <el-input v-if="isEditing" v-model="studentInfo.section"></el-input>
                    <span v-else>{{ studentInfo.section }}</span>
                </el-form-item>
            </div>
            <div class="info-row">
                <label>手机号</label>
                <el-form-item prop="telephone">
                    <el-input v-if="isEditing" v-model="studentInfo.telephone"></el-input>
                    <span v-else>{{ studentInfo.telephone }}</span>
                </el-form-item>
                <label>Email</label>
                <el-form-item prop="email">
                    <el-input v-if="isEditing" v-model="studentInfo.email" type="email"></el-input>
                    <span v-else>{{ studentInfo.email }}</span>
                </el-form-item>
            </div>
            <button v-if="!isEditing" @click="startEditing">编辑信息</button>
            <button v-if="isEditing" @click="saveInfo">保存信息</button>
        </el-form>

        <!-- 修改密码 -->
        <el-form :model="form" :rules="rules" ref="passwordForm" class="password-section">
            <h3>旧密码</h3>
            <el-form-item prop="password">
                <el-input type="password" placeholder="请输入旧密码" v-model="form.password" show-password />
            </el-form-item>
            <h3>新密码</h3>
            <el-form-item prop="newPass">
                <el-input type="password" placeholder="请输入密码" v-model="form.newPass" show-password />
            </el-form-item>
            <h3>确认密码</h3>
            <el-form-item prop="repassword">
                <el-input type="password" placeholder="请输入确认密码" v-model="form.repassword" show-password />
            </el-form-item>
            <button @click="onSubmit">确认修改</button>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { useStore } from "vuex"
import { useRouter } from "vue-router"
import { updatepassword } from "~/api/manager"
import { showModal, toast } from "~/composables/util"
import { computed } from 'vue'
import request from "~/utils/request.js"
import { serverIp } from "~/utils/config.js";

const infoForm = ref(null)
const passwordForm = ref(null)
const isEditing = ref(false)
const router = useRouter()
const store = useStore()
const studentInfo = reactive({
    id: store.state.user.id,
    username: store.state.user.username,
    className: store.state.user.className,
    age: store.state.user.age,
    telephone: store.state.user.telephone,
    unit: store.state.user.unit,
    department: store.state.user.department,
    section: store.state.user.section,
    email: store.state.user.email,
    sex: store.state.user.sex,
    photo: store.state.user.photo
})

// 添加响应式更新
watch(() => store.state.user, (newUser) => {
    Object.assign(studentInfo, {
        id: newUser.id,
        username: newUser.username,
        className: newUser.className,
        age: newUser.age,
        telephone: newUser.telephone,
        unit: newUser.unit,
        department: newUser.department,
        section: newUser.section,
        email: newUser.email,
        sex: newUser.sex,
        photo: newUser.photo
    })
}, { deep: true })

const form = reactive({
    userId: computed(() => store.state.user.id),
    password: "",
    newPass: "",
    repassword: ""
})

const rules = reactive({
    password: [
        {
            required: true,
            message: '旧密码不能为空',
            trigger: 'blur'
        },
    ],
    newPass: [
        {
            required: true,
            message: '新密码不能为空',
            trigger: 'blur'
        },
    ],
    repassword: [
        {
            required: true,
            message: '确认密码不能为空',
            trigger: 'blur'
        },
    ],
    sex: [
        {
            required: true,
            message: '请选择性别',
            trigger: 'change'
        }
    ],
    age: [
        {
            required: true,
            message: '年龄不能为空',
            trigger: 'blur'
        },
        {
            type: 'number',
            message: '年龄必须为数字',
            trigger: 'blur'
        },
        {
            validator: (rule, value, callback) => {
                if (value < 1 || value > 100) {
                    callback(new Error('年龄必须在1到100岁之间'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    telephone: [
        {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur'
        },
        {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
        }
    ],
    email: [
        {
            required: true,
            message: '邮箱不能为空',
            trigger: 'blur'
        },
        {
            type: 'email',
            message: '邮箱格式不正确',
            trigger: 'blur'
        }
    ]
})

const onSubmit = () => {
    passwordForm.value.validate(valid => {
        if (!valid) {
            toast("请正确填写表单", "error")
            return false
        }

        if (form.newPass !== form.repassword) {
            toast("两次密码不一致", "warning")
            return false
        }

        updatepassword(form)
            .then(res => {
                if (res.data.code === "600") {
                    toast(res.data.msg, 'error')
                    return false
                }
                toast("修改密码成功，请重新登录")
                store.dispatch("logout")
                // 跳转回登录页
                router.push("/login")
            })
    })
}

const startEditing = () => {
    isEditing.value = true
}

const saveInfo = () => {
    infoForm.value.validate(valid => {
        if (!valid) {
            toast("请正确填写表单", "error")
            return false
        }

        request.post("/user/stuUpdateUserInfo", studentInfo).then(res => {
            if (res.code === "200") {
                store.commit('updateUserPhoto', studentInfo.photo)
                toast("修改成功")
            } else {
                toast("修改失败，请稍后重试")
            }
        })

        isEditing.value = false
    })
}

const checkFileType = (file) => {
    const maxSize = 1024 * 1024 * 1024;
    if (file.size > maxSize) {
        this.$message.warning('文件大小超过1GB限制!');
        return false;
    }
    return true;
}

const photoHandleSuccess = (response) => {
    studentInfo.photo = `/api/file/download/${response}`
    saveInfo()
}

const photoHandleError = () => {
    toast("上传文件失败")
}
</script>

<style scoped>
.student-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.avatar-section {
    text-align: center;
    margin-bottom: 20px;
}

.avatar {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    object-fit: cover;
    margin-bottom: 10px;
}

.info-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    width: 100%;
}

.info-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-top: 20px;
    align-items: center;
}

.info-row label {
    color: #666;
    font-weight: 500;
}

.info-row input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.interest-course,
.password-section {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    width: 100%;
}

.password-section input {
    display: block;
    width: 300px;
    margin: 10px 0;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.password-section button,
.info-section button {
    background: #409eff;
    color: white;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-top: 20px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
